package com.zzyl.nursing.service.impl;

import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-19
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住管理
     *
     * @param id 入住管理主键
     * @return 入住管理
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住管理列表
     *
     * @param checkIn 入住管理
     * @return 入住管理
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住管理
     *
     * @param checkIn 入住管理
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住管理
     *
     * @param checkIn 入住管理
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住管理
     *
     * @param ids 需要删除的入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住管理信息
     *
     * @param id 入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 新增入住申请
     *
     * @param applyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto applyDto) {
        //获取所有dto信息(入参)
        CheckInElderDto elderInfo = applyDto.getCheckInElderDto();  // 老人信息
        List<ElderFamilyDto> familyInfo = applyDto.getElderFamilyDtoList();  // 家属信息
        CheckInConfigDto checkInInfo = applyDto.getCheckInConfigDto();  // 入住信息
        CheckInContractDto contractInfo = applyDto.getCheckInContractDto();  // 合同签约信息
        //根据身份证号和状态判断老人是否入住(入住则抛异常)
        Elder elder = elderMapper.selectOne
                (new LambdaQueryWrapper<Elder>()
                        .eq(Elder::getIdCardNo, elderInfo.getIdCardNo())
                        .eq(Elder::getStatus, 1));
        if (ObjectUtil.isNotNull(elder)) {
            throw new BaseException("该老人已入住");
        }
        //获取床位信息并更新(未入住)
        Bed bed = bedMapper.selectBedById(checkInInfo.getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);//Todo
        //新增or更新老人
        elder = insertOrUpdateElder(elderInfo, bed);
        //新增签约合同
        insertContract(contractInfo, elder, checkInInfo);
        //新增入住信息(家属)
        Long checkInId = insertCheckInInfo(elder, checkInInfo, bed, familyInfo);
        //新增合同配置信息
        insertCheckInConfig(checkInInfo, checkInId);

    }

    /**
     * 查询入住详(反显) 0220
     *
     * @param checkinID
     */
    @Override
    public CheckInDetailVo detailCheckInById(Long checkinID) {
        //1、查询入住信息
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectById(checkinID);
        //2.获取老人办理信息
        Elder elder = this.elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        if (ObjectUtil.isNotNull(elder)){
            BeanUtils.copyProperties(elder, checkInElderVo);
        }
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);


        //3、查询入住配置信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        if (ObjectUtil.isNotNull(checkIn)){
            BeanUtils.copyProperties(checkIn, checkInConfigVo);
        }
        CheckInConfig checkInConfig = checkInConfigMapper
                .selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, checkinID));
        if (ObjectUtil.isNotNull(checkIn)){
            BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        }
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //4.查询家属信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);


        //5.获取签约办理信息
        Contract contract = this.contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, elder.getId()).eq(Contract::getStatus, 1));
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;


    }


    /**
     * 入住合同信息
     *
     * @param checkInInfo
     * @param checkInId
     */
    private void insertCheckInConfig(CheckInConfigDto checkInInfo, Long checkInId) {
        CheckInConfig checkInConfig = new CheckInConfig();
        // 1、拷贝填充入住配置信息
        BeanUtil.copyProperties(checkInInfo, checkInConfig);

        // 2、填充入住信息ID
        checkInConfig.setCheckInId(checkInId);

        // 3、新增
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 家属信息
     *
     * @param elder
     * @param checkInInfo
     * @param bed
     * @param familyInfo
     * @return
     */
    private Long insertCheckInInfo(Elder elder, CheckInConfigDto checkInInfo, Bed bed, List<ElderFamilyDto> familyInfo) {
        CheckIn checkIn = new CheckIn();
        // 1、填充老人信息
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());

        // 2、填充入住信息
        checkIn.setStartDate(checkInInfo.getStartDate());
        checkIn.setEndDate(checkInInfo.getEndDate());
        checkIn.setNursingLevelName(checkInInfo.getNursingLevelName());

        // 3、填充床位信息
        checkIn.setBedNumber(bed.getBedNumber());

        // 4、填充家属信息
        checkIn.setRemark(JSONUtil.toJsonStr(familyInfo));
        checkInMapper.insert(checkIn);

        return checkIn.getId();
    }

    /**
     * 合同信息
     *
     * @param contractInfo
     * @param elder
     * @param checkInInfo
     */
    private void insertContract(CheckInContractDto contractInfo, Elder elder, CheckInConfigDto checkInInfo) {
        // 1、拷贝填充合同签约信息
        Contract contract = new Contract();
        BeanUtils.copyProperties(contractInfo, contract);

        // 2、填充老人信息
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());

        // 3、填充合同的开始结束日期、合同编号、状态
        contract.setStartDate(checkInInfo.getStartDate());
        contract.setEndDate(checkInInfo.getEndDate());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setStatus(1);

        // 4、新增
        contractMapper.insert(contract);
    }

    /**
     * 老人表信息
     *
     * @param elderInfo
     * @param bed
     * @return
     */

    private Elder insertOrUpdateElder(CheckInElderDto elderInfo, Bed bed) {
        // 1.填充老人信息
        Elder elder = new Elder();
        BeanUtil.copyProperties(elderInfo, elder);

        // 2、填充床位信息
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());

        // 3、查询老人是否曾经入住过
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, elderInfo.getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder elderInDb = elderMapper.selectOne(queryWrapper);

        if (ObjectUtil.isNull(elderInDb)) {
            // 4、没有查询到记录，未入住过：新增
            elderMapper.insert(elder);
        } else {
            // 5、查询到了记录，入住过：更新
            elder.setStatus(1);
            elderMapper.updateById(elder);
        }
        return elder;
    }
}
